package com.ruoyi.project.hcy.product.controller;

import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.hcy.product.domain.img.ProImg;
import com.ruoyi.project.hcy.product.service.IProImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @ClassName ProImgController
 * @Author SAI
 * @Date 2020/9/18 23:29
 * @Description ProImgController
 * @Version 1.0
 */
@Controller
@RequestMapping("/hcy/product/ProImg")
public class ProImgController {

    @Autowired
    private IProImgService proImgService;

    @RequestMapping("/add")
    @ResponseBody
    public ProImg add(@RequestParam("imgFile")MultipartFile imgFile, HttpServletRequest request) throws IOException {
        //获取上传文件的名称
        String fileName = imgFile.getOriginalFilename();
        //解决文件重名问题
        String newFileName = UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf("."));
        String  finalFileName= newFileName.replaceAll("-", "");
        //获取上传文件的路径
//      文件需要源码目录和class目录双向保存
        String property = System.getProperty("user.dir");
        String origin = property + "/src/main/resources/static/img/hcy/";
        //编译文件目录
        String target = this.getClass().getClassLoader().getResource("").getPath() + "static/img/hcy/";
//        保存文件两次
        File originPath = new File(origin);
        File targetPath = new File(target);
        File originFile = new File(originPath, finalFileName);
        File targetFile = new File(targetPath, finalFileName);

        InputStream is = imgFile.getInputStream();
        FileOutputStream ofos = new FileOutputStream(originFile);
        byte[] oBytes = new byte[1024];
        int oLen =0;
        while ((oLen=is.read(oBytes))!= -1) {
            ofos.write(oBytes,0,oLen);
            ofos.flush();
        }

        InputStream inputStream = imgFile.getInputStream();
        FileOutputStream tfos = new FileOutputStream(targetFile);
        byte[] tBytes = new byte[1024];
        int bLen =0;
        while ((bLen=inputStream.read(tBytes)) != -1) {
            tfos.write(tBytes,0,bLen);
            tfos.flush();
        }
        is.close();
        ofos.close();
        tfos.close();


//        imgFile.transferTo(originFile);
//        imgFile.transferTo(targetFile);
        return proImgService.insertUrl(finalFileName);
    }
}


